import { reactive } from 'vue'

// 用户状态
const userState = reactive({
  operator: '',
  project_name: '',
  count: '',
  software_version: '',
  trace_barcode: '',
  isLoggedIn: false,
  loginTime: null
})

// 用户状态管理方法
export const userStore = {
  // 获取状态
  getState() {
    return userState
  },

  // 设置用户登录信息
  setUser(userInfo) {
    // 支持传入对象或字符串（向后兼容）
    if (typeof userInfo === 'string') {
      userState.operator = userInfo
      userState.project_name = ''
      userState.count = ''
      userState.software_version = ''
      userState.trace_barcode = ''
    } else {
      userState.operator = userInfo.operator || ''
      userState.project_name = userInfo.project_name || ''
      userState.count = userInfo.count || ''
      userState.software_version = userInfo.software_version || ''
      userState.trace_barcode = userInfo.trace_barcode || ''
    }
    
    userState.isLoggedIn = true
    userState.loginTime = new Date()
    
    // 保存到本地存储，防止刷新丢失
    localStorage.setItem('plc_user', JSON.stringify({
      operator: userState.operator,
      project_name: userState.project_name,
      count: userState.count,
      software_version: userState.software_version,
      trace_barcode: userState.trace_barcode,
      isLoggedIn: true,
      loginTime: userState.loginTime
    }))
  },

  // 通用字段更新方法
  _updateField(fieldName, value, displayName) {
    userState[fieldName] = value || ''
    
    // 更新本地存储，保持其他字段不变
    try {
      const savedUser = localStorage.getItem('plc_user')
      let userData = {}
      
      if (savedUser) {
        userData = JSON.parse(savedUser)
      }
      
      // 更新指定字段
      userData[fieldName] = userState[fieldName]
      
      // 保存回本地存储
      localStorage.setItem('plc_user', JSON.stringify(userData))
    } catch (error) {
      console.error(`更新${displayName}到本地存储失败:`, error)
    }
  },

  // 通用字段获取方法
  get(fieldName) {
    return userState[fieldName] || ''
  },

  // 通用字段设置方法
  set(fieldName, value) {
    this._updateField(fieldName, value, fieldName)
  },

  // 检查是否已登录
  isLoggedIn() {
    return userState.isLoggedIn
  },

  // 用户登出
  logout() {
    userState.operator = ''
    userState.project_name = ''
    userState.count = ''
    userState.software_version = ''
    userState.trace_barcode = ''
    userState.isLoggedIn = false
    userState.loginTime = null
    
    // 清除本地存储
    localStorage.removeItem('plc_user')
  },

  // 从本地存储恢复用户状态
  restoreFromStorage() {
    try {
      const savedUser = localStorage.getItem('plc_user')
      if (savedUser) {
        const userData = JSON.parse(savedUser)
        userState.operator = userData.operator || ''
        userState.project_name = userData.project_name || ''
        userState.count = userData.count || ''
        userState.software_version = userData.software_version || ''
        userState.trace_barcode = userData.trace_barcode || ''
        userState.isLoggedIn = userData.isLoggedIn || false
        userState.loginTime = userData.loginTime ? new Date(userData.loginTime) : null
      }
    } catch (error) {
      console.error('恢复用户状态失败:', error)
      this.logout() // 如果恢复失败，清除状态
    }
  }
}

// 应用启动时恢复状态
userStore.restoreFromStorage()

export default userStore